class ProductA < ActiveRecord::Base
  extend Enumerize

  mount_uploader :logo, LogoUploader

  validates :name, presence: true
  enumerize :category, in: [:internet_software, :internet_hardware], default: :internet_software, scope: true

  has_many :screenshots, class_name: 'Image', as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :screenshots, allow_destroy: true

  belongs_to :user

  def updateScreenshot screens, delete_screens
    if screens
      screens.each do |id|
        Image.find(id).update(imageable_id: self.id)
      end
    end
    unless delete_screens.blank?
      delete_screens.split(',').each do |id|
        Image.find(id).destroy
      end
    end
  end

  def last_financing
    f = ['天使轮', 'A轮', 'B轮', 'C轮', 'D轮', '已上市']
    financings.nil? ? '未融资' : financings.map{|fi| fi['stage']}.compact.sort_by{|st| f.index(st)}.last
  end

  def as_my_json
    {
      logo: logo.url || '/assets/default_logo.jpg',
      name: name,
      category: I18n.t("activerecord.attributes.product.category.#{category}"),
      financing: last_financing,
      cowork: cowork_records.blank? ? '无' : '有',
      updated_at: updated_at.strftime('%Y/%m/%d'),
      user: user.try(:username),
      edit_path: Rails.application.routes.url_helpers.edit_admin_product_a_path(id: id),
      path: Rails.application.routes.url_helpers.admin_product_a_path(id: id)
    }
  end

  class << self
    def search keyword
      product_as = all
      keyword ? product_as.where('lower(name) like ?', "%#{keyword.downcase}%") : product_as
    end

    def filter category, financing
      product_as = all
      product_as = product_as.where(category: category) unless category == ''
      # TODO performance
      product_as = product_as.select{|p| p.last_financing == financing} unless financing == ''
      product_as = ProductA.where(id: product_as.map(&:id))
      product_as
    end
  end

end
